import 'dart:math';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class PageStateTable extends StatelessWidget {
  const PageStateTable({super.key, required this.state});

  final List<int> state;

  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(20.0),
      alignment: Alignment.topLeft,
      decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(
        side: BorderSide(
          width: 0,
          color: Theme.of(context).colorScheme.primary,
          style: BorderStyle.solid,
        ),
      )),
      child: _buildFilePageState(context),
    );
  }

  Widget _buildFilePageState(BuildContext context) {
    RenderBox? renderBox = context.findRenderObject() as RenderBox?;
    if (renderBox == null) {
      return const Text("分页状态区初始化完成");
    }
    if (state.isEmpty) {
      return const Text("请扫描文件分页二维码");
    }
    double cell = calTableCellSize(
        state.length, renderBox.size.width - 40, renderBox.size.height - 40);
    List<Widget> rect = [];
    ThemeData theme = Theme.of(context);
    for (int i = 0; i < state.length; ++i) {
      int s = state[i];
      rect.add(Container(
          width: cell,
          height: cell,
          alignment: Alignment.center,
          decoration: ShapeDecoration(
              color: mapStateToColor(s, theme),
              shape: RoundedRectangleBorder(
                side: BorderSide(
                  width: 0,
                  color: theme.colorScheme.primary,
                  style: BorderStyle.solid,
                ),
              )),
          child: Text("${i + 1}")));
    }
    return Wrap(children: rect);
  }

  Color mapStateToColor(int s, ThemeData theme) {
    switch (s) {
      case 0:
        return theme.brightness == Brightness.light
            ? Colors.black26
            : Colors.white30;
      case 1:
        return theme.brightness == Brightness.light
            ? Colors.green
            : const Color.fromARGB(255, 0, 120, 60);
      case 2:
        return theme.brightness == Brightness.light
            ? Colors.orange
            : Colors.deepOrange;
    }
    return Colors.grey;
  }

  double calTableCellSize(int count, double width, double height) {
    double scale = height / width;
    double x = sqrt(count / scale);
    // 从最少填充开始计算
    for (int num1 in [x.floor(), x.ceil(), x.ceil() + 1]) {
      double size1 = width / num1;
      int num2 = max(1, (height / size1).floor());
      double size2 = height / num2;
      if (num1 * num2 >= count) {
        return min(size1, size2);
      }
    }
    {
      // 最保守的方案，可能填充不满，理论上不会执行到这里
      double maxX = sqrt(width * height / count);
      int minN1 = (width / maxX).ceil();
      int minN2 = (count / minN1).ceil();
      double maxS1 = width / minN1;
      double maxS2 = height / minN2;
      return min(maxS1, maxS2);
    }
  }
}
